<template>
  <div class="editWrapper">
    <h3>发表文章</h3>
    <div>
      <label class="labelBox">
        标题
        <el-input v-model="textData.title"
          placeholder="请输入内容"
          class="inputStyle">
        </el-input>
      </label>
      <label class="labelBox">
        作者
        <el-input
          v-model="textData.author"
          class="littleStyle">
        </el-input>
        标签
        <el-select 
          v-model="textData.tagsId" 
          multiple placeholder="请选择不超过3个标签"
          @change="checkTags"
          class="littleStyle">
          <el-option
            v-for="item in tags"
            :key="item.id"
            :label="item.tagName"
            :value="item.id">
          </el-option>
        </el-select>
      </label>
      <el-upload
        action="http://newsplatform.hfutonline.net/onlineNewsPlatform/images/imagesUpload"
        name="img"
        :with-credentials="true"
        list-type="picture-card"
        :file-list="filelist"
        :headers="token"
        :on-preview="handlePictureCardPreview"
        :on-error="uploadErr"
        :on-success="uploadCover"
        class="imgBox">
        <i class="el-icon-plus"></i>
        <div slot="tip" class="el-upload__tip">上传封面图</div>
      </el-upload>
      <label class="labelArea">
        摘要
        <el-input
          type="textarea"
          class="littleStyle" 
          :rows="4"
          placeholder="请输入内容"
          v-model="textData.summary">
        </el-input>
      </label>
      <el-upload
        action="http://newsplatform.hfutonline.net/onlineNewsPlatform/images/imagesUpload"
        name="img"
        :with-credentials="true"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-error="uploadErr"
        :headers="token"
        :on-success="uploadSuccess"
        class="imgBox">
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog v-model="dialogVisible" size="tiny">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
      <span class="tips">(选择jpg/png图片上传)</span>
    </div>
    <vue-editor v-model="textData.content"></vue-editor>
    <el-button type="info" @click="sendNews" class="sendBtn">发表文章</el-button>
  </div>
</template>

<script>
  import { VueEditor } from 'vue2-editor'
  import { mapGetters, mapActions } from 'vuex'
  
  export default {
    name: 'EditNews',
    data () {
      return {
        textData: {
          title: '',
          tagsId: [],
          images: [],
          content: '',
          coverUrl: '',
          userId: 1,
          author: '',
          summary: ''
        },
        token: {
          token: ''
        },
        filelist: [],
        permission: true,
        dialogImageUrl: '',
        dialogVisible: false,
        editorOption: {
          theme: 'bubble',
          modules: {
            toolbar: '#toolbar'
          }
        }
      }
    },
    computed: {
      ...mapGetters([
        'msg',
        'tags'
      ])
    },
    created () {
      this.$store.dispatch('getAllTags')
      this.token.token = window.localStorage.token
    },
    watch: {
      msg (val) {
        let cur = val[val.length - 1]
        if (cur.state === 'fail') {
          this.$message.error(cur.msg)
        } else {
          this.$message({
            type: 'success',
            message: cur.msg
          })
        }
      }
    },
    components: {
      VueEditor
    },
    methods: {
      ...mapActions([
        'postNews',
        'getAllTags'
      ]),
      checkTags (val) {
        if (val.length > 3) {
          this.$message.error('标签不能超过3个，请重新选择')
          this.textData.tagsId = []
        }
      },
      uploadErr (err) {
        this.$message.error('由于某种不可抗力，图片上传失败了')
        console.log(err)
      },
      uploadCover (res, file) {
        console.log(res)
        if (res.flag === true) {
          this.$message({
            message: '封面上传成功',
            type: 'success'
          })
          this.textData.coverUrl = res.resultStr
          this.filelist = [].concat(file)
        } else {
          this.$message.error(res.resultStr)
        }
      },
      uploadSuccess (res, file) {
        if (res.flag === true) {
          this.$message({
            message: '图片上传成功',
            type: 'success'
          })
          let images = document.querySelector('.ql-editor')
          let img = document.createElement('img')
          img.src = res.resultStr
          img.style.width = '60%'
          img.style.display = 'block'
          img.style.margin = '0 auto'
          images.appendChild(img)
          this.textData.images.push({
            description: this.textData.title,
            url: res.resultStr
          })
        } else {
          this.$message.error(res.resultStr)
        }
      },
      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      sendNews () {
        let sendData = {}
        for (let key in this.textData) {
          if (this.textData[key] === '') {
            this.$message({
              message: '是不是少填了点东西呢',
              type: 'error'
            })
            this.permission = false
            break
          } else {
            sendData[key] = this.textData[key]
          }
        }
        if (this.permission) {
          this.$store.dispatch('postNews', { params: sendData })
          .then(() => {
            this.$message({
              message: '新闻发布成功',
              type: 'success'
            })
          })
          for (let key in this.textData) {
            if (key === 'tagsId') {
              this.textData[key] = []
            } else {
              this.textData[key] = ''
            }
          }
          this.permission = true
        }
      }
    }
  }
</script>

<style lang="stylus" scoped>
  .editWrapper
    width: 75%
    margin: 20px auto
    border: 1px solid #ccc
    overflow: hidden
    h3
      width: 100%
      line-height: 50px
      background: #e5e5e5
      padding-left: 20px
      box-sizing: border-box
    .imgBox
      padding: 20px
    .tips
      display: inline-block
      margin-left: 20px
      color: #ccc
    .labelArea
      display: flex
      justify-content: flex-start
      align-items: center
      box-sizing: border-box
      padding: 20px
      width: 80%
      .littleStyle
        width: 80%
        margin: 0 10px
    .labelBox
      display: flex
      justify-content: flex-start
      align-items: center
      box-sizing: border-box
      padding: 20px
      width: 80%
      height: 60px
      .inputStyle
        width: 80%
        margin-left: 10px
      .littleStyle
        width: 40%
        margin: 0 10px
    .sendBtn
      float: right
      margin: 20px
</style>
